<script>
/* Numeric only validation
function isNumberKey(event){
		var charCode=window.event?event.keyCode:event.which;
		if(event.keyCode==8||event.keyCode==9||event.keyCode==46||event.keyCode==37||event.keyCode==39){
			return true;
		} else if (charCode<48||charCode>57){
			return false;
		} else 
			return true;
	}
	*/
$(document).ready(function(){
//Initialize all components.
var methodOfPaymentContainer=$('#MethodOfPaymentContainer').buttonset();
var dateIn=$('#DateIn').datepicker({dateFormat:'MM dd, yy'});
var dateCompleted=$('#DateCompleted').datepicker({dateFormat:'MM dd, yy'});
var dateEFiled=$('#DateEFiled').datepicker({dateFormat:'MM dd, yy'});
var dateFiled=$('#DateFiled').datepicker({dateFormat:'MM dd, yy'});
var dateCollected=$('#DateCollected').datepicker({dateFormat:'MM dd, yy'});
// Initialize all Dialogs and hide them.
var personalClientDialog=$('#PersonalClientDialog').dialog({
	autoOpen:false,
	title:"Personal Client",
	modal:true,
	resizable:false,
	width:1200,
	height:600,
	buttons:{
		"Save":function(){
			var client={
				"clientId":($('#clientId')!=undefined?$('#clientId').val():''),
				"ClientNumber":$('#PersonalClientForm #ClientNumber').val(),
				"FirstName":$('#PersonalClientForm #FirstName').val(),
				"LastName":$('#PersonalClientForm #LastName').val(),
				"Email":$('#PersonalClientForm #Email').val(),
				"HomePhone":$('#PersonalClientForm #HomePhone').val(),
				"CellPhone":$('#PersonalClientForm #CellPhone').val(),
				"WorkPhone":$('#PersonalClientForm #WorkPhone').val(),
				"NumberOfReturns":$('#PersonalClientForm #NumberOfReturns').val(),
				"NumberOfReturnsCompleted":$('#PersonalClientForm #NumberOfReturnsCompleted').val(),
				"NumberOfReturnsSigned":$('#PersonalClientForm #NumberOfReturnsSigned').val(),
				"NumberOfReturnsEFiled":$('#PersonalClientForm #NumberOfReturnsEFiled').val(),
				"DateEFiled":($('#PersonalClientForm #DateEFiled').datepicker('getDate')!=undefined?$('#PersonalClientForm #DateEFiled').datepicker('getDate').getTime():''),
				"NumberOfReturnsPaperFiled":$('#PersonalClientForm #NumberOfReturnsPaperFiled').val(),
				"DateFiled":($('#PersonalClientForm #DateFiled').datepicker('getDate')!=undefined?$('#PersonalClientForm #DateFiled').datepicker('getDate').getTime():''),
				"DateIn":($('#PersonalClientForm #DateIn').datepicker('getDate')!=undefined?$('#PersonalClientForm #DateIn').datepicker('getDate').getTime():''),
				"DateCompleted":($('#PersonalClientForm #DateCompleted').datepicker('getDate')!=undefined?$('#PersonalClientForm #DateCompleted').datepicker('getDate').getTime():''),
				"Fee":$('#PersonalClientForm #Fee').val(),
				"DateCollected":($('#PersonalClientForm #DateCollected').datepicker('getDate')!=undefined?$('#PersonalClientForm #DateCollected').datepicker('getDate').getTime():''),
				"Accountant":($('#PersonalClientForm #AccountantContainer option:selected').val()),
				"FeeCollected":($('#PersonalClientForm #FeeCollected').val()),
				"MethodOfPayment":$('#PersonalClientForm #MethodOfPaymentContainer option:selected').val(),
				"Note":($('#PersonalClientForm #Note').val())
			};
			var hasError=false;
			// Validation on required fields.
			$('#PersonalClientForm .RequiredField').each(function(){
				var field=$('#PersonalClientForm #'+$(this).attr('for'));
				$('#PersonalClientForm #'+field.attr('id')+'Message').empty();
				if(field.attr('id')=='AccountantContainer'){
					if($('#PersonalClientForm #AccountantContainer :input[name="Accountant"]').val()===undefined){
						hasError=true;
						$('#PersonalClientForm #'+field.attr('id')+'Message').append('Required');
					}
				}else{
					var value=field.val();
					if(value===undefined||value==''){
						$('#PersonalClientForm #'+field.attr('id')+'Message').append('Required');
						hasError=true;
					}else{
						$('#PersonalClientForm #'+field.attr('id')+'Message').empty();
					}
				}
			});
			// Validate numeric fields
			$('#PersonalClientForm .Numeric').each(function(){
				$('#PersonalClientForm #'+$(this).attr('id')+'Message').empty();
				if(!$(this).val().match("^[0-9]*$")){
					hasError=true;
					$('#PersonalClientForm #'+$(this).attr('id')+'Message').append('Numerics only');
				}
			});
			// Validate decimal fields
			$('#PersonalClientForm .Decimal').each(function(){
				$('#PersonalClientForm #'+$(this).attr('id')+'Message').empty();
				if(!$(this).val().match("^[0-9]+\\.?[0-9]*$")||$(this).val().charAt($(this).val().length-1)=='.'){
					hasError=true;
					$('#PersonalClientForm #'+$(this).attr('id')+'Message').append('Decimals only');
				}
			});
			if(!hasError){
				$.ajax({
					url:"/SavePersonalClient",
					type:"POST",
					dataType:"json",
					data:client,
					success:function(data,status,xhr){
						// After saving successfully, redirect back to client.jsp with ID.
						window.location.href='/GetPersonalClient?clientId='+data.clientId;
					},
					error:function(xhr,status,error){
						alert("error:"+error);
					}
				});
			}
		},
		Cancel:function(){	   
       			$(this).dialog("close");
		}
	},
	open:function(){
		// If ID field is empty, then set all defaults.  If not, set all values.
		if($('#clientId').val()!=undefined){
			// Retrieve client info.
			// Get all users
			/*$.ajax({
				url:'/AjaxGetUsers',
				type:'GET',
				dataType:'json',
				success:function(data,status,xhr){
					var accountantContainer=$('#PersonalClientForm #AccountantContainer').empty();
					var users=data.data;
					var currentUserId='<%=((String)request.getAttribute("CurrentUserId"))%>';
					for(var i=0;i<users.length;i++){
						if(users[i].UserId==currentUserId){
							accountantContainer.append('<input id="'+users[i].UserId+'" name="Accountant" type="radio" value="'+users[i].UserId+'" checked="checked"/><label for="'+users[i].UserId+'">'+users[i].Nickname+'</label>');
						}else{
							accountantContainer.append('<input id="'+users[i].UserId+'" name="Accountant" type="radio" value="'+users[i].UserId+'"/><label for="'+users[i].UserId+'">'+users[i].Nickname+'</label>');
						}
					}
					accountantContainer.buttonset();
				},
				error:function(xhr,status,error){
					alert('Error:'+error);
				}
			});*/
			$.ajax({
				url:'/AjaxGetClient',
				type:'GET',
				dataType:'json',
				data:{
					clientId:$('#clientId').val()
				},
				success:function(data,status,xhr){
					var accountantContainer=$('#PersonalClientForm #AccountantContainer').empty();
					/*define dummy data
					var usersObj=[
						{
							key:"Acc1",
							value:"Andy",
							note: "Name"},
						{
							key:"Acc2",
							value:"Simon"},
						{"Acc3":"John"},
						{"Acc4":"Peter"}
					];

					// print json keys
						    alert("User Key: "+users[i].userId+",Value: "+users[i].Nickname);
						    var keys=Object.keys(users[i]);
						    for(var j=0;j<keys.length;j++){
						    	alert("Keys: "+keys[j]);
					}*/

					if(data.success==true){
						var client=data.data.client;
						var a=client.Accountant;
						var users=data.data.users;						
						var select="<select name='Accountant'>";
						for(var i=0;i<users.length;i++){
							if (users[i].key==a) {
								select+="<option value='"+users[i].userId+"' selected='selected'>"+users[i].Nickname+"</option>";
							}else{
								select+="<option value='"+users[i].userId+"'>"+users[i].Nickname+"</option>";
							}
						} 
						select += "</select>";
						accountantContainer.append(select);
						/*
						var select="<select name='Accountant'>";
						for(var i=0;i<usersObj.length;i++){
							select+="<option value='"+usersObj[i].key+"'";
							if (usersObj[i].key==a) {
								select+="' selected='selected'"
							}
							select+=">"+usersObj[i].value+"</option>";
						} 
						select += "</select>";
						*/
						$('#PersonalClientForm :input:text').each(function(index,element){
							$(this).val(client[$(this).attr('name')]);
						});
						$('#PersonalClientForm :input:radio').each(function(index,element){
							if(client[$(this).attr('name')]==$(this).attr('id')){
								$(this).attr('checked','checked').button('refresh');
							}
						});
						$('#PersonalClientForm :input:checkbox').each(function(index,element){
							if(client[$(this).attr('name')]!=undefined){
								if(client[$(this).attr('name')]=='true'){
									$(this).attr('checked','checked').button('refresh');
								}else{
									$(this).removeAttr('checked').button('refresh');
								}
							}
						});
						$('#PersonalClientForm #Note').append((client.Note!=undefined?client.Note:''));
						// display saved Method of Payment
						var mop=data.data.client.MethodOfPayment;
						var m=document.getElementById("MethodOfPaymentOption");
						for(var i=0,j=m.options.length;i<j;++i){
							if (m.options[i].innerHTML==mop){
								m.selectedIndex=i;
								break;
							}
						}
					}else{
						alert('Error:'+data.error);
					}
				},
				error:function(xhr,status,error){
					alert('Error:'+error);
				}
			});
		}else{
			// Get all users
			$.ajax({
				url:'/AjaxGetUsers',
				type:'GET',
				dataType:'json',
				success:function(data,status,xhr){
					var accountantContainer=$('#PersonalClientForm #AccountantContainer').empty();
					var users=data.data;
					var currentUserId='<%=((String)request.getAttribute("CurrentUserId"))%>';
					var select="<select name='Accountant'>";
						for(var i=0;i<users.length;i++){
							if (currentUserId==users[i].userId) {
								select+="<option value='"+users[i].userId+"' selected='selected'>"+users[i].Nickname+"</option>";
							}else{
								select+="<option value='"+users[i].userId+"'>"+users[i].Nickname+"</option>";
							}
						} 
						select += "</select>";
					accountantContainer.append(select);
					//accountantContainer.buttonset();
				},
				error:function(xhr,status,error){
					alert('Error:'+error);
				}
			});	
		}
	},
	close:function(){
		// Clear all fields and reset defaults for radios.
		$('#PersonalClientForm :input[type="text"],textarea').val('');
		$('#PersonalClientForm #AccountantContainer').empty();
		$('#PersonalClientForm .Message').empty();
	}
	});
});
</script>
<div id="PersonalClientDialog">
<form id="PersonalClientForm">
<table>
	<tr>
		<td><label id="ClientNumberLabel" for="ClientNumber" class="RequiredField">Client No:</label></td><td><input id="ClientNumber" name="ClientNumber" type="text" maxlength="30" size="30"/><label id="ClientNumberMessage" class="Message" for="ClientNumber"></label></td>
		<td></td><td></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td><label id="NameLabel" for="LastName" class="RequiredField">Last Name:</label></td><td><input id="LastName" name="LastName" type="text" maxlength="100" size="30" placeholder="Last Name"/><label id="LastNameMessage" class="Message" for="LastName"></label></td>
		<td>First Name:</td><td><input id="FirstName" name="FirstName" type="text" maxlength="100" size="30"/ placeholder="First Name"></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td>Email:</td><td><input id="Email" name="Email" type="text" size="30" placeholder="username@domain.com"/></td>
		<td></td><td></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td>Home Phone:</td><td><input id="HomePhone" name="HomePhone" type="text" maxlength="16" size="16"/></td>
		<td>Cell Phone:</td><td><input id="CellPhone" name="CellPhone" type="text" maxlength="16" size="16"/></td>
		<td>Work Phone:</td><td><input id="WorkPhone" name="WorkPhone" type="text" maxlength="16" size="16"/></td>
	</tr>
	<tr>
		<td>Date In:</td><td><input id="DateIn" name="DateIn" type="text"/></td>
		<td>Date Completed:</td><td><input id="DateCompleted" name="DateCompleted" type="text"/></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td>No. Of Returns:</td><td><input class="Numeric" id="NumberOfReturns" name="NumberOfReturns" type="text" maxlength="5" size="5"/><label id="NumberOfReturnsMessage" class="Message" for="NumberOfReturns"></label></td>
		<td>No. Of Returns Completed:</td><td><input class="Numeric" id="NumberOfReturnsCompleted" name="NumberOfReturnsCompleted" type="text" maxlength="5" size="5"/><label id="NumberOfReturnsCompletedMessage" class="Message" for="NumberOfReturnsCompleted"></label></td>
		<td>No. Of Returns Signed:</td><td><input class="Numeric" id="NumberOfReturnsSigned" name="NumberOfReturnsSigned" type="text" maxlength="5" size="5"/><label id="NumberOfReturnsSignedMessage" class="Message" for="NumberOfReturnsSigned"></label></td>
	</tr>
	<tr>
		<td>No. Of Returns EFiled:</td><td><input class="Numeric" id="NumberOfReturnsEFiled" name="NumberOfReturnsEFiled" type="text" maxlength="5" size="5"/><label id="NumberOfReturnsEFiledMessage" class="Message" for="NumberOfReturnsEFiled"></label></td>
		<td>Date EFiled:</td><td><input id="DateEFiled" name="DateEFiled" type="text"/></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td>No. Of Returns Paper Filed:</td><td><input class="Numeric" id="NumberOfReturnsPaperFiled" name="NumberOfReturnsPaperFiled" type="text" maxlength="5" size="5"/><label id="NumberOfReturnsPaperFiledMessage" class="Message" for="NumberOfReturnsPaperFiled"></label></td>
		<td>Date Filed:</td><td><input id="DateFiled" name="DateFiled" type="text"/></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td>Fee:</td><td><input class="Decimal" id="Fee" name="Fee" type="text" maxlength="6" size="6" /><label id="FeeMessage" class="Message" for="Fee"></label></td>
		<td>Date Collected:</td><td><input id="DateCollected" name="DateCollected" type="text"/></td>
	</tr>
	<tr>
		<td>Method Of Payment:</td>
		<td>
			<div id="MethodOfPaymentContainer" style="float:left;">
				<select id="MethodOfPaymentOption">
					<option value="None">None</option>
					<option value="Cash">Cash</option>
					<option value="Cheque">Cheque</option>
					<option value="Card">Card</option>
				</select>
			</div>
		</td>
		<td>Fee Collected:</td><td><input class="Decimal" id="FeeCollected" name="FeeCollected" type="text" maxlength="5" size="5"/><label id="FeeCollectedMessage" class="Message" for="FeeCollected"></label></td>
		<td></td><td></td>
	</tr>
	<tr>
		<td><label for="AccountantContainer" id="AccountantLabel" class="RequiredField">Accountant:</label></td><td>
		<div id="AccountantContainer"></div><label id="AccountantContainerMessage" class="Message" for="AccountantContainer"></label>
		</td>
	</tr>
	<tr>
		<td>Note:</td><td colspan="5"><textarea id="Note" name="Note" rows="5" cols="60"></textarea></td>
	</tr>
</table>
</form>
</div>